package functionalTest;

import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.time.Duration;

public class LoginTest extends AutotestUtils{

    // 正常登录
    @Test
    public void testLogin() throws IOException {
        loginTest("zhangsan", "123456");
    }

    // 异常登录
    @Test
    public void testLogin2() throws IOException {
        // 用户名正确, 密码错误
        loginTest("zhangsan", "1234567");
    }

    @Test
    public void testLogin3() throws IOException {
        // 用户名错误, 密码正确
        loginTest("zhangsan1111", "123456");
    }

    @Test
    public void testLogin4() throws IOException {
        // 用户名密码均错误
        loginTest("zha456ngsan", "1234567");
    }

    @Test
    public void testLogin5() throws IOException {
        // 密码正确,用户名为空
        loginTest("", "123456");
    }

    @Test
    public void testLogin6() throws IOException {
        // 用户名正确, 密码为空
        loginTest("zhangsan", "");
    }

    public void loginTest(String username, String password) throws IOException {
        // 找到登录元素
        WebElement login = webDriver.findElement(By.id("signIn"));
        login.click(); // 点击该元素

        // 找到输入用户名元素
        WebElement inputName = webDriver.findElement(By.id("username"));
        inputName.sendKeys(username);

        // 找到输入密码元素
        WebElement inputPassword = webDriver.findElement(By.id("password"));
        inputPassword.sendKeys(password);

        // 点击登录
        WebElement button = webDriver.findElement(By.cssSelector("#submit"));
        // 使用 JavaScript 触发点击
        JavascriptExecutor js = (JavascriptExecutor) webDriver;
        js.executeScript("arguments[0].click();", button);

        // 等待弹窗出现
        wait.until(ExpectedConditions.alertIsPresent());
        // 切换到弹窗
        Alert alert = webDriver.switchTo().alert();
        // 获取弹窗信息
        String text = alert.getText();
        // 结束弹窗
        alert.accept();

        boolean isLoginSuccess = isLoginSuccessful();
        if (isLoginSuccess) {
            System.out.println("登录成功：" + text);
            AutotestUtils.getScreenShot(webDriver);
        }else {
            System.out.println("登录失败：" + text);
            AutotestUtils.getScreenShot(webDriver);
        }
    }

    // 确认是否登录成功并跳转页面
    private boolean isLoginSuccessful() {
        try {
            // 登录成功
            // 检查新页面是否成功跳转
            wait.until(ExpectedConditions.urlToBe("http://47.120.16.255:8081/game_hall.html"));
            return true;
        }catch (Exception e) {
            return false;
        }
    }
}
